package org.vox.homepage.infra

import javax.servlet.http.{HttpServletRequest, HttpServletResponse}

import org.slf4j.LoggerFactory
import org.springframework.web.servlet.{HandlerInterceptor, ModelAndView}

/**
  * @author merlin
  */
class GeneralInterceptor extends HandlerInterceptor {
  import GeneralInterceptor.logger

  override def postHandle(request: HttpServletRequest, response: HttpServletResponse, handler: scala.Any, modelAndView: ModelAndView) : Unit = ???

  override def afterCompletion(request: HttpServletRequest, response: HttpServletResponse, handler: scala.Any, ex: Exception) : Unit = {
    val duration = System.currentTimeMillis() - request.getAttribute("request_start_time").asInstanceOf[Long]

    val serviceName = request.getPathInfo

    logger.info("[{}] take {}ms", serviceName, duration)
  }

  override def preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: scala.Any) : Boolean = {
    request.setAttribute("request_start_time", System.currentTimeMillis())
    true
  }
}

object GeneralInterceptor {
  val logger = LoggerFactory.getLogger(classOf[GeneralInterceptor])
}
